﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JWT;
using System.Runtime.Caching;

namespace WZVTC.SoftDev.WebUtility
{
    public class JWTHelper
    {
        static string  secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
        static int expOver = 10*60;
        static private MemoryCache mc = new MemoryCache("NonceCache");
        static private Random ro = new Random();
        public static string GetNonce(string uID,int expireSecond=60*10)
        {

            if(!mc.Contains(uID))
            {
                mc.Add(uID, ro.Next().ToString(), new DateTimeOffset(DateTime.Now+TimeSpan.FromSeconds(expireSecond)));
            }
            return (mc.Get(uID)) as string;
            
            
        }
        public static string GetToken(string uID,string role)
        {
            var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
           var now = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds);
           now += expOver;
            var payload = new Dictionary<string, object>()
             {
                       { "userID", uID },
                      { "role", role },
                      {"exp",now}
             };
          
            string token="";
            try
            {
                 token = JWT.JsonWebToken.Encode(payload, secretKey, JWT.JwtHashAlgorithm.HS256);
            }
            catch(Exception ex)
            {}
            return token;
            
        }
        public static bool Verify(string token,string uID)
        {
            try
            {
                var payload = JWT.JsonWebToken.DecodeToObject(token, secretKey, true) as Dictionary<string,object>;
                if (payload["userID"].Equals(uID))
                    return true;
                else return false;
            }
            catch(SignatureVerificationException ex)
            {
                return false;
            }
        }
    }
}
